<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./lib/bootstrap.css" />
  <script src="./lib/jquery.js"></script>
</head>

<body>
  <!-- 1. 文件选择框 -->
  <input type="file" id="file1" />
  <!-- 2. 上传文件的按钮 -->
  <button id="btnUpload">上传文件</button>

  <!-- bootstrap 中的进度条 -->
  <div class="progress" style="width: 500px; margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
     0%
    </div>
  </div>

  <br />
  <!-- 3. img 标签，来显示上传成功以后的图片 -->
  <img src="" alt="" id="img" width="800" />

  <script>
    // 接口地址： http://www.liulongbin.top:3006/api/upload/avatar

    // 1. 获取到文件上传按钮
    const btnUpload = document.querySelector('#btnUpload')
    const fileInput = document.querySelector('#file1')
    const img = document.querySelector('#img')
    const percent = document.querySelector('#percent')
   
    // 2. 为按钮绑定单击事件处理函数
    btnUpload.addEventListener('click',function(){
        if(fileInput.files.length === 0){
            return alert('请选择上传的文件')
        }
        const fd = new FormData()
        fd.append('avatar',fileInput.files[0])
        const xhr = new XMLHttpRequest()

        // 文件上传进度
        xhr.upload.onprogress = function(e){
            if(e.lengthComputable){
                const percentComplete = Math.ceil((e.loaded /e.total) *100)
                percent.style.width = `${percentComplete}%`
                percent.innerHTML = `${percentComplete}%`
            }
        }

        // 文件上传完成
        xhr.upload.onload = function(){
            percent.className = 'progress-bar progress-bar-success'
        }
        xhr.open('POST','http://www.liulongbin.top:3006/api/upload/avatar')
        xhr.send(fd)
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                const {status,url,message} = JSON.parse(xhr.responseText)
                if(status === 200){
                    img.src = `http://www.liulongbin.top:3006${url}`
                }else{
                    console.log(`图片上传失败${message}`)   
                }
            }
        }
    })





  </script>
</body>

</html>